<template>
  <div class="user-management-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <img src="/logo.png" alt="家政服务平台" />
          <span>家政服务平台</span>
        </div>
        <el-icon><Menu /></el-icon>
        <el-icon><Refresh /></el-icon>
        <span class="nav-text">用户管理</span>
      </div>
      <div class="header-right">
        <el-button class="client-btn">
          <el-icon><Monitor /></el-icon>
          客户端
        </el-button>
        <el-badge is-dot>
          <el-icon><Bell /></el-icon>
        </el-badge>
        <el-icon><Setting /></el-icon>
        <el-dropdown @command="handleCommand">
          <div class="user-info">
            <el-avatar :size="32">{{ userInitials }}</el-avatar>
            <span>{{ username }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="settings">账号设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <span style="color: #f56c6c;">注销</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="main-container">
      <!-- 左侧菜单 -->
      <el-aside width="64px" class="sidebar">
        <router-link to="/admin" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><HomeFilled /></el-icon>
            <span>首页</span>
          </div>
        </router-link>
        <router-link to="/admin/service-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><Setting /></el-icon>
            <span>服务管理</span>
          </div>
        </router-link>
        <router-link to="/admin/user-management" custom v-slot="{ navigate }">
          <div class="menu-item active" @click="navigate">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </div>
        </router-link>
        <router-link to="/admin/application-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><Promotion /></el-icon>
            <span>审批系统</span>
          </div>
        </router-link>
        <router-link to="/admin/worker-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><User /></el-icon>
            <span>家政管理</span>
          </div>
        </router-link>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main-content">
        <div class="user-management">
          <div class="page-header">
            <h2>用户账户管理</h2>
          </div>

          <!-- 用户搜索筛选 -->
          <div class="filter-container">
            <el-form :inline="true" :model="searchForm" class="search-form">
              <el-form-item label="账号">
                <el-input v-model="searchForm.account" placeholder="请输入账号" clearable />
              </el-form-item>
              <el-form-item label="角色类型">
                <el-select
                    v-model="searchForm.role"
                    placeholder="请选择角色"
                    clearable
                    popper-class="role-select-dropdown"
                    :popper-append-to-body="false"
                    style="width: 100%;">
                  <template #prefix v-if="searchForm.role">
                    <el-tag size="small" :type="getRoleTagType(searchForm.role)" class="role-tag">
                      {{ getRoleName(searchForm.role) }}
                    </el-tag>
                  </template>
                  <el-option
                      v-for="item in roleOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    <div style="display: flex; align-items: center;">
                      <el-tag size="small" :type="getRoleTagType(item.value)" style="margin-right: 8px;">
                        {{ item.label }}
                      </el-tag>
                      <span>{{ item.label }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :data="users" v-loading="loading" style="width: 100%; margin-top: 20px" border table-layout="fixed">
            <!-- 移除了角色ID列 -->
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="account" label="账号" align="center" />
            <el-table-column prop="role" label="角色类型" align="center">
              <template #default="scope">
                <el-tag :type="getRoleTagType(scope.row.role)">
                  {{ getRoleName(scope.row.role) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  HomeFilled, Menu, Setting, Bell, Monitor, CaretBottom, Refresh,
  User, Promotion
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {deleteUserById, getUserList, userLogout} from "@/api/user/user.js";

const router = useRouter()
const username = ref('admin')
const userInitials = computed(() => {
  return username.value.charAt(0).toUpperCase()
})

// 角色选项
const roleOptions = [
  { label: '管理员', value: 'admin' },
  { label: '家政人员', value: 'worker' },
  { label: '客户', value: 'client' }
]

// 获取角色名称
const getRoleName = (role) => {
  const found = roleOptions.find(item => item.value === role)
  return found ? found.label : '未知'
}

// 获取角色标签类型
const getRoleTagType = (role) => {
  switch(role) {
    case 'admin': return 'danger'
    case 'worker': return 'warning'
    case 'client': return 'success'
    default: return 'info'
  }
}

// 页面状态
const loading = ref(false)
const users = ref([])
// 存储所有用户数据，用于前端搜索
const allUsers = ref([])

// 搜索表单
const searchForm = reactive({
  account: '',
  role: ''
})

// 加载数据
onMounted(async () => {
  await fetchUsers()
})

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await getUserList()
    console.log(response.data.data)
    if (response.data.code === 200) {
      // 同时保存到 allUsers 和 users
      allUsers.value = response.data.data
      users.value = [...allUsers.value]
    } else {
      ElMessage.warning(response.data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 搜索处理 - 前端实现搜索功能
const handleSearch = () => {
  // 从保存的所有用户数据中进行过滤
  users.value = allUsers.value.filter(user => {
    let matchAccount = true
    let matchRole = true

    // 账号过滤 - 如果输入了搜索条件则进行过滤
    if (searchForm.account && searchForm.account.trim() !== '') {
      matchAccount = user.account.toLowerCase().includes(searchForm.account.toLowerCase())
    }

    // 角色过滤 - 如果选择了角色则进行过滤
    if (searchForm.role && searchForm.role.trim() !== '') {
      matchRole = user.role === searchForm.role
    }

    // 同时满足账号和角色条件的记录
    return matchAccount && matchRole
  })
}

// 重置搜索 - 重置为显示所有数据，使用本地缓存
const resetSearch = () => {
  searchForm.account = ''
  searchForm.role = ''
  // 直接使用已经缓存的所有用户数据，无需重新请求
  users.value = [...allUsers.value]
}

// 编辑用户
const handleEdit = (row) => {
  ElMessageBox.confirm(`确定要编辑用户 ${row.account} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际编辑逻辑
    ElMessage.success('编辑请求已发送')
  }).catch(() => {})
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.account} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteUserById(row.id)
      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        // 删除成功后更新本地数据
        const index = allUsers.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          allUsers.value.splice(index, 1)
        }
        // 更新当前显示的用户列表
        users.value = users.value.filter(user => user.id !== row.id)
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }).catch(() => {})
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    logout()
  } else if (command === 'profile') {
    router.push('/admin/profile')
  } else if (command === 'settings') {
    router.push('/admin/settings')
  }
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await userLogout()
    } finally {
      localStorage.removeItem('token')
      router.push('/login')
    }
  }).catch(() => {})
}
</script>

<style scoped>
/* 样式保持不变 */
:deep(.el-header), :deep(.el-aside), :deep(.el-main) {
  padding: 0;
  margin: 0;
}

:deep(.el-main) {
  --el-main-padding: 20px;
  padding: var(--el-main-padding);
}

.user-management-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
  position: absolute;
  left: 0;
  top: 0;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  z-index: 1000;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 20px;
  font-weight: bold;
  font-size: 18px;
}

.logo img {
  height: 32px;
  margin-right: 8px;
}

.nav-text {
  margin-left: 15px;
}

.header-left .el-icon {
  margin-right: 15px;
  font-size: 18px;
  cursor: pointer;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .el-icon {
  font-size: 20px;
  margin: 0 15px;
  cursor: pointer;
}

.client-btn {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
}

.user-info span {
  margin: 0 8px;
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  width: 100%;
  margin: 0;
  padding: 0;
}

.sidebar {
  background-color: #fff;
  height: 100%;
  box-shadow: 1px 0 4px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  z-index: 900;
  width: 64px !important;
  min-width: 64px;
  flex-shrink: 0;
  margin: 0;
  padding-left: 0;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 64px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
}

.menu-item span {
  font-size: 12px;
  margin-top: 5px;
}

.menu-item .el-icon {
  font-size: 20px;
}

.menu-item.active {
  color: #1989fa;
  background-color: #f0f7ff;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  width: calc(100% - 64px);
  box-sizing: border-box;
}

.user-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 22px;
  margin: 0;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

/* 添加以下表格样式 */
:deep(.el-table) {
  width: 100%;
  table-layout: fixed;
}

/* 使表头居中 */
:deep(.el-table th) {
  text-align: center;
}

/* 使表格单元格内容垂直居中 */
:deep(.el-table td) {
  vertical-align: middle;
}
</style>